/**
 * Created by user on 2015/9/22.
 */

angular.module('mis.activityManager.controllers', [])
    .controller('activityCtrl', ['$scope','$http', '$location', function ($scope, $http, $location) {

        $scope.currentPage = 1;
        $scope.pageSize = 15;

        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/activity/activityList/:page/:size',
            ajax: $http,
            success:function(data){
                $scope.activityList = GetCategoryName(data.data.list,'image');
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
            },
            error: function(err){
                //$scope.communityList = null;
            },
            params: {}
        });
        //,'_up'
        //全选列表
        $scope.allSelected = function () {
            $scope.pagination.allSelected();
        };

        $scope.selectFile = function (file,model,type) {
            if (model == 'add') {
                if(type =='share'){
                    document.getElementById("image_share").innerHTML = '';
                }else{
                    document.getElementById("image_result").innerHTML = '';
                }

            }else{
                if(type =='share'){
                    document.getElementById("image_share_edit").innerHTML = '';
                }else{
                    document.getElementById("image_result_edit").innerHTML = '';
                }
            }
            showImages(model,type);
        };

        var reader = null;
        var readerShare = null;

        if (FileReader) {
            reader = new FileReader();
            readerShare = new FileReader();
        } else {
            alert("浏览器暂时不支持FileReader");
        }
        var imageEle;
        var fileList = {}, length = 0, length1 = 0;
        var fileListShare = {};
        var showImages = function (model,type) {

            if(model =='add'){
                if(type =='share'){
                    var imageEleShare  = document.getElementById("images_upload_share");
                }else {
                    var imageEle = document.getElementById("images_upload");

                }
            }else{
                if(type =='share'){
                    var imageEleShare  = document.getElementById("images_upload_share_edit");
                }else {
                    var imageEle = document.getElementById("images_upload_edit");
                };
            }

            if(type == 'share'){
                //获取上传的分享图片
                fileListShare = imageEleShare.files;
            }else{
                //获取上传的多个文件
                fileList = imageEle.files;
                length = fileList.length;
                length1 = fileList.length;
            }

            //获取文件信息
            readURL(model,type);
        };

        var readURL = function (model,type) {

            if(type =='share'){

                readerShare.readAsDataURL(fileListShare[0]);
                readerShare.onload = function () {
                    var img = document.createElement("img");
                    img.src = readerShare.result;
                    img.width = 200;
                    if (model == 'add') {
                        document.getElementById("image_share").appendChild(img);
                    } else {
                        document.getElementById("image_share_edit").appendChild(img);
                    }
                };

            }else {

                reader.readAsDataURL(fileList[length1 - length]);
                reader.onload = function () {
                    var img = document.createElement("img");
                    img.src = reader.result;
                    img.width = 200;
                    if (model == 'add') {
                        document.getElementById("image_result").appendChild(img);
                    } else {
                        document.getElementById("image_result_edit").appendChild(img);
                    }
                    length--;
                    if (length == 0)return;
                    readURL(model, type);
                };

            }
        };

        //新增
        $scope.add = function(addData, temp){

            var target = temp.target;

            if (!addData) {
                alert('请填写标题和描述!'); return;
            };
            if (!addData.title) {
                alert('标题不能为空!'); return;
            };
            if (!addData.desc) {
                alert('描述不能为空!'); return;
            };
            if (!addData.shareDesc) {
                alert('分享描述不能为空!'); return;
            };

            var opt = {
                title : addData.title
                ,desc : addData.desc
                ,shareDesc : addData.shareDesc
                ,address : addData.address
                ,type: (!addData.type) ? 0 : addData.type
                ,explain : addData.explain
                ,charge : addData.charge
                ,beginDate : addData.beginDate
                ,endDate : addData.endDate
            };

            var fd = new FormData();
            var index = 0;
            if (fileListShare != null) {
                if(fileListShare.length>0) {
                    fd.append('image1', fileListShare[0]);
                    index =1;
                };
            };

            if (fileList != null) {
                for (var i = 0; i < fileList.length; i++) {
                    index = index + 1;
                    fd.append('image' + index, fileList[i]);
                };
            };

            $('#doc-modal-add').modal("close");
            
            $('#loading').modal({target: '#loading'});

            if (fileList.length>0  || fileListShare.length>0) {
                if(fileList.length>6){
                    alert('上传图片不能超过6张!');
                    return;
                };
                //上传图片
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {

                    var uploadImages = [];
                    for(var i=0;i<images.data.length;i++) {
                        if (images.data[i] != null) {
                            //如果存在shareImage取第一张图片
                            if(fileListShare.length>0 && i==0){
                                opt.shareImage = images.data[i];
                            }else{
                                uploadImages.push({imageURL:images.data[i]})
                            };
                        };

                    };
                    opt.images = uploadImages;
                    console.debug(opt);
                    $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/activity/activityAdd', opt, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        $scope.addData = {};
                        $scope.pagination.selectPage(1);//插入成功显示第一页
                        $('#doc-modal-add').modal("close");
                        $('#loading').modal('close');
                        alert("添加活动成功");

                    }).error(function (err) {
                        alert(err);
                    });

                });

            }else{
                console.debug(opt);
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/activity/activityAdd', opt, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.addData = {};
                    $scope.pagination.selectPage(1);//插入成功显示第一页
                    $('#doc-modal-add').modal("close");
                    alert("添加活动成功");

                }).error(function (err) {
                    alert(err);
                });
            };

        };

        //删除
        $scope.delete = function(){
            var params = {
                url: 'http://' + backOfficeHost + '/rest/v1.0/mis/activity/activityDelete',
                checkObj: $(".item-check"),//checkbox对象
                key: "activityID",
                success: function(data){
                    var number = $(".am-active").text();//当前页码
                    $scope.pagination.selectPage(number);
                    alert("删除成功！");

                },
                error: function(){}
            };
            $scope.pagination.listDelete(params);
        };

        $scope.updateData = {};
        $scope.activityEdit = function(activity){

            fileList = {};
            fileListShare = {};
            activity.beginDate = (new Date(activity.beginDate)).format('yyyy-MM-dd hh:mm');
            activity.endDate = (new Date(activity.endDate)).format('yyyy-MM-dd hh:mm');
            $scope.updateData = activity;


            $('#doc-modal-edit').modal({target: '#doc-modal-edit', width: 800, height: 600 });
        };

        $scope.updateActivity = function(updateData) {

            $('#doc-modal-edit').modal("close");

            if (!updateData.title) {
                alert('标题不能为空!'); return;
            };
            if (!updateData.desc) {
                alert('描述不能为空!'); return;
            };
            if (!updateData.shareDesc) {
                alert('分享描述不能为空!'); return;
            };
            //if (!updateData.charge) {
            //    alert('费用不能为空!'); return;
            //};
            $('#loading').modal({target: '#loading'});
            //console.debug(updateData);
            var uData = {id:updateData.objId, activity:{}};
            //if(updateData.objId)uData.secondHandID = updateData.objId;
            if(updateData.title != null)uData.activity.title = updateData.title;
            if(updateData.desc != null)uData.activity.desc = updateData.desc;
            if(updateData.type != null)uData.activity.type = updateData.type;
            if(updateData.address != null)uData.activity.address = updateData.address;
            if(updateData.explain != null)uData.activity.explain = updateData.explain;
            if(updateData.charge != null)uData.activity.charge = updateData.charge;
            if(updateData.beginDate != null)uData.activity.beginDate = updateData.beginDate;
            if(updateData.endDate != null)uData.activity.endDate = updateData.endDate;
            if(updateData.shareDesc != null)uData.activity.shareDesc = updateData.shareDesc;
            if(updateData.shareKey != null)uData.activity.shareKey = updateData.shareKey;

            var fd = new FormData();
            var index = 0;
            if (fileListShare != null) {
                if(fileListShare.length>0) {
                    fd.append('image1', fileListShare[0]);
                    index =1;
                };
            };

            if (fileList != null) {
                for (var i = 0; i < fileList.length; i++) {
                    index = index + 1;
                    fd.append('image' + index, fileList[i]);
                }
            };


            if (fileList.length>0 || fileListShare.length>0) {

                //上传图片
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {

                    var uploadImages = [];
                    for(var i=0;i<images.data.length;i++) {
                        if (images.data[i] != null) {
                            //如果存在shareImage取第一张图片
                            if(fileListShare.length>0 && i==0){
                                uData.activity.shareImage = images.data[i];
                            }else{
                                uploadImages.push({imageURL:images.data[i]})
                            };
                        };
                    };
                    if (fileList.length>0 && uploadImages.length>0) {
                        uData.activity.images = uploadImages;
                    }
                    console.debug(uData);
                    $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/activity/activityEdit', uData, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        //$('#doc-modal-edit').modal("close");
                        $('#loading').modal('close');
                        $('#image_result_edit').empty();
                        $('#image_share_edit').empty();
                        $scope.search(true);
                        alert("修改成功");
                    }).error(function (err) {
                        $('#loading').modal('close');
                        $('#image_result_edit').empty();
                        $('#image_share_edit').empty();
                        alert(err);
                    });

                });

            }else {

                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/activity/activityEdit', uData, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $('#loading').modal('close');
                    //var pageNumber = $(".am-active").text();//当前页码
                    if (data.result.status == 1) {
                        $('#loading').modal('close');
                        $('#image_result_edit').empty();
                        $('#image_share_edit').empty();
                        //$scope.pagination.selectPage(pageNumber);
                        $scope.search(true);
                        alert('修改成功!');
                    } else {
                        alert('修改失败!');
                    }
                }).error(function (err) {
                    $('#loading').modal('close');
                    $('#image_result_edit').empty();
                    $('#image_share_edit').empty();
                    //var number = $(".am-active").text();//当前页码
                    //$('#doc-modal-edit').modal("close");
                    alert("修改失败！");
                });

            }

        };

        //搜索
        $scope.search = function (temp) {

            var current = temp.target;

            if (current) {
                $scope.currentPage = $scope.pagination.currentPage;
            }else {
                $scope.pagination.currentPage = 1;
                $scope.currentPage = 1;
            }

            //var community = $scope.cascading.getVillageId(target);
            var body = {};

            if ($scope.title) body.title = $scope.title;
            if ($scope.type) body.type = $scope.type;
            //if ($("#beginDate").val()) body.beginDate = $("#beginDate").val() + ' 00:00:00';
            //if ($("#endDate").val()) body.endDate = $("#endDate").val() + ' 23:59:59';
            if ($scope.beginDate) body.beginDate = $scope.beginDate;
            if ($scope.endDate) body.endDate = $scope.endDate;
            console.debug(body);
            if (body.beginDate && body.endDate && body.beginDate > body.endDate) {
                alert('开始日期不能大于结束日期');
                return;
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/activity/activityList/' + $scope.currentPage + '/' + $scope.pageSize, body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.activityList = GetCategoryName(data.data.list,'image');
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;

                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $scope.pagination.searchParams = body;
            }).error(function (err) {
                $scope.goodsList = null;
                alert(err);
            });
        };

        //查看参加活动人员信息
        $scope.partakerShow = function(activity){

            console.debug(activity);

            $scope.showData = activity;

            $('#doc-modal-partaker').modal({target: '#doc-modal-partaker', width: 800, height: 600 });

            //分页
            $scope.pagination_partaker = new pagination({currentPage:1,pageSize: $scope.pageSize,
                url:'http://' + backOfficeHost + '/rest/v1.0/mis/activity/partakerList/:page/:size',
                ajax: $http,
                success:function(data){
                    $scope.partakerList = data.data.list;
                    $scope.pageNumber_partaker = data.data.totalPage;
                    $scope.count_partaker = data.data.count;
                    $scope.currentPage_partaker = $(".am-active").text();
                    $scope.pagination_partaker.totalPage = data.data.totalPage;
                    $scope.pagination_partaker.pageHeader($scope.pageNumber_partaker);
                    $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
                },
                error: function(err){
                    //$scope.communityList = null;
                },
                params: {activity:activity.objId}
            },'_partaker');


        };

        //导出
        $scope.export = function(){

            var idArray = [];
            var params = {};
            var ids = "";
            var checkObj = $(".item-check");

            for(var i = 0;i < checkObj.length;i++){
                if(checkObj[i].checked == true){
                    idArray.push(checkObj[i].parentNode.parentNode.id);
                    ids += checkObj[i].parentNode.parentNode.id +',';
                }
            };

            ids = ids.substr(0,ids.length-1);

            if(idArray.length == 0){alert("请选择导出列表项！");return;}else {
                if(!confirm("确认要导出吗？"))return;
            };

            var url = 'http://' + backOfficeHost + '/rest/v1.0/mis/activity/exportPartaker/?ids='+ids;


            location.href = url;

        };

        $scope.activityPushShow = function(activity){

            $scope.activityPush = activity;
            $scope.activityPush.msg =''

            //$scope.message = {
            //    tag: '专题',
            //    //content: message.title,
            //    //uList: uList,
            //    type: 1,
            //    url: activity.url,
            //    openType: 4,
            //    //contentId: activity.objId,
            //    desc: title
            //};

            $('#doc-modal-push').modal({target: '#doc-modal-push', width: 800, height: 360 });

        };

        //$scope.setMessage = function(){
        //
        //};

        $scope.activityPushMsg = function(msg){

            if($scope.activityPush.partakerCount == 0){
                alert('参加活动人数为0不能推送!');
                return;
            };

            if(!$scope.pushMsg){
                alert('请填写推送内容!');
                return;
            };

            var opt = {
                    activityId : $scope.activityPush.objId,
                    //tag: '专题',
                    ////content: message.title,
                    ////uList: uList,
                    //type: 1,
                    //url: $scope.activityPush.url,
                    //openType: 4,
                    //contentId: activity.objId,
                    desc: msg
            };

            console.debug(opt);
            $('#doc-modal-push').modal("close");

            $('#pushLoading').modal({target: '#pushLoading'});

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/activity/activityPush', opt,{
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (data.result.status == 1) {
                    $('#pushLoading').modal("close");
                    alert("活动消息推送成功！");
                }else {
                    $('#pushLoading').modal("close");
                    alert("活动消息推送失败！");
                    //$scope.pagination.selectPage($scope.currentPage);
                }

            }).error(function (err) {
                $('#pushLoading').modal("close");
                alert("活动消息推送失败！");
                //$scope.pagination.selectPage($scope.currentPage);
            });

        };



    }])